import asyncio
import datetime
import time

from django.conf.locale import bs
from django.shortcuts import render
from rest_framework import status

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Book
from .serializer import BookSerializer, BookSerializer2, BookSerializer3


class BookView(APIView):
    def get(self, request):
        # httpx.get(request)
        book = Book.objects.filter(title='将进酒')
        if not book:
            return Response({'error': 'Book not found'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        bs = BookSerializer(instance=book[0])
        return Response(bs.data)


class BookReverseView(APIView):
    def get(self, request):
        '''
        模拟反序列化，但是真正反序列化需要post，put
        '''
        print("第一步")
        bs = BookSerializer(data={"title": "Django小王子", "price": 100,  "publish_id": 1, "publish_name":"123123"})
        if bs.is_valid():  # 必须先要is_valid,才会有bs.validated_data和bs.errors
            # bs.save()
            return Response(bs.validated_data)
        else:
            return Response(bs.errors)
        # bs.validated_data


class BookView2(APIView):
    def get(self, request):
        books = Book.objects.all()
        bs = BookSerializer2(instance=books, many=True)
        return Response(bs.data)
    def post(self, request):
        bs = BookSerializer2(data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

class BookView2Detail(APIView):
    def get(self, request, pk):
        book = Book.objects.get(pk=pk)
        bs = BookSerializer2(instance=book)
        return Response(bs.data)

    def put(self, request, pk):
        instance = Book.objects.get(pk=pk)
        bs = BookSerializer2(instance=instance, data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def delete(self, request, pk):
        instance = Book.objects.get(pk=pk).delete()
        return Response('delete success', status=status.HTTP_200_OK)

class BookView3(APIView):
    def get(self, request):
        books = Book.objects.all()
        bs = BookSerializer3(instance=books, many=True)
        return Response(bs.data)

    def post(self, request):
        bs = BookSerializer3(data=request.data)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)